<template>
  <div class="app-container">
    <div class="searchBox">
      <el-form :inline="true" :model="search" ref="searchForm">
        <el-form-item label="任务名称:" prop="name">
          <el-input v-model="search.shakyName" name="shakyName" placeholder="请输入内容"></el-input>
        </el-form-item>
        <el-form-item label="创建人:" prop="createdUserName">
          <el-input v-model="search.createdUserName" name="createdUserName" placeholder="请输入内容"></el-input>
        </el-form-item>
        <el-form-item style="margin-top: -2px">
          <el-button type="primary" @click="searchQuery">查询</el-button>
          <el-button type="info" @click="search = {};searchQuery()">重置</el-button>
        </el-form-item>
      </el-form>
    </div>

    <qm-table
      ref="shakyTable"
      keyProp="shakyId"
      menuType="text"
      :data="query"
      :showView="false"
      :showCheckbox="false"
      :formOptions="{ labelWidth: '120px' }"
      :modalOptions="{ height: 500 ,width:900}"
      :menuOptions="{width:'200px'}"
      :rules="rules"
    >
      <qm-table-column field="shakyName" show-overflow>任务名称</qm-table-column>
      <qm-table-column field="startDate" width="180px">任务开始时间</qm-table-column>
      <qm-table-column field="endDate" width="180px">任务结束时间</qm-table-column>
      <qm-table-column field="leaveDay" width="130px">工作量时间(小时)</qm-table-column>
      <qm-table-column field="createdUserName" width="100px">创建人姓名</qm-table-column>
      <qm-table-column field="createdDeptName" width="150px">创建人部门</qm-table-column>
      <template v-slot:form="{model}">
        <el-alert
          title="温馨提示"
          type="info"
          description="不可以跨天选择时间喔,时间范围在09:00-18:00,选择时间后工作量时间自动生成喔。"
          show-icon
        ></el-alert>
        <el-form-item style="margin-top: 15px;" label="任务名称：" prop="model.shakyName">
          <el-input v-model="model.shakyName" placeholder="请输入"></el-input>
        </el-form-item>
        <el-form-item style="margin-bottom: 0px;" label="任务时间：" required>
          <el-col :span="7">
            <el-form-item prop="model.startDate">
              <el-date-picker
                @change="changeVa(model)"
                style="width: 100%;"
                v-model="model.startDate"
                type="datetime"
                value-format="yyyy-MM-dd HH:mm:ss"
                placeholder="选择日期时间"
                :picker-options="{selectableRange: '09:00:00 - 18:00:00'}"
                :clearable="false"
              ></el-date-picker>
            </el-form-item>
          </el-col>
          <el-col style="width: 2%;" :span="2">至</el-col>
          <el-col :span="7">
            <el-form-item prop="model.endDate">
              <el-date-picker
                @change="changeVa(model)"
                style="width: 100%;"
                v-model="model.endDate"
                type="datetime"
                value-format="yyyy-MM-dd HH:mm:ss"
                placeholder="选择日期时间"
                :picker-options="{selectableRange: '09:00:00 - 18:00:00'}"
                :clearable="false"
              ></el-date-picker>
            </el-form-item>
          </el-col>
        </el-form-item>
        <el-form-item label="工作量时间：" prop="model.leaveDay">
          <el-col :span="7">
            <el-input disabled placeholder="计算已加入工作日" v-model="model.leaveDay">
              <template slot="append">小时</template>
            </el-input>
          </el-col>
        </el-form-item>
        <el-form-item label="备注：" prop="model.reason">
          <el-input type="textarea" :rows="5" placeholder="请输入内容" v-model="model.reason"></el-input>
        </el-form-item>
      </template>
      <template v-slot:moreBtn="{ row }">
        <el-button @click="handleCommand(row)" size="mini" type="text">添加参与人员</el-button>
      </template>
    </qm-table>
    <el-dialog
      :title="row.shakyName+'添加参与人员'"
      :visible.sync="dialogUserVisible"
      @closed="dialogUserClose"
      width="60%"
      :close-on-click-modal="false"
      :close-on-press-escape="false"
    >
      <el-alert
        title="温馨提示"
        type="info"
        description="添加人员后会对应生成该人员当天的工作日报喔(任务小时数对应日报的工作的小时数),重复添加会对数据进行合并处理。"
        show-icon
      ></el-alert>
      <el-row style="margin-top: 20px;">
        <el-col :span="4">
          <el-select
            v-model="searchUsers"
            value-key="value"
            multiple
            filterable
            remote
            placeholder="请输入关键词"
            :remote-method="remoteMethod"
          >
            <el-option
              v-for="item in users"
              :key="item.userId"
              :label="`${item.label}（${item.loginId}）`"
              :value="item.userId"
            ></el-option>
          </el-select>
        </el-col>
        <el-col :span="2">
          <el-button
            style="margin-left: 10px;"
            type="primary"
            @click="addUsers"
            icon="el-icon-plus"
          >添加</el-button>
        </el-col>
        <el-col :span="4" :offset="1">
          <el-cascader
            v-model="departmentId"
            clearable
            :options="deptTree"
            :show-all-levels="false"
            :props="{value:'id',label:'text',
            multiple: true, checkStrictly: true }"
          ></el-cascader>
        </el-col>
        <el-col :span="2">
          <el-button
            style="margin-left: 10px;"
            type="warning"
            @click="batchAddUsers"
            icon="el-icon-plus"
          >根据部门添加</el-button>
        </el-col>
        <el-col style="margin-top: 5px;" :span="4" :offset="2">
          <el-radio-group v-model="sex">
            <el-radio :label="1">女</el-radio>
            <el-radio :label="0">男</el-radio>
          </el-radio-group>
        </el-col>
        <el-col :span="2">
          <el-button type="success" @click="addUsersBySex" icon="el-icon-plus">根据性别添加</el-button>
        </el-col>
      </el-row>
      <el-row style="margin-top: 20px;">
        <el-col :span="18">
          <el-input
            type="textarea"
            :autosize="{ minRows: 3, maxRows: 5}"
            placeholder="请输入姓名以，分隔，例：张三，李四（或换行符、空格）"
            v-model="names"
          ></el-input>
        </el-col>
        <el-col :span="3" :offset="1">
          <el-button type="primary" @click="addUsersByNames" icon="el-icon-plus">根据姓名添加</el-button>
        </el-col>
      </el-row>
      <qm-table
        style="margin-top: -30px;"
        ref="userTable"
        v-if="dialogUserVisible"
        :urls="{query:'/eip/shaky/shakyMembers'}"
        :beforeQuery="beforeQuery"
        :showView="false"
        :showEdit="false"
        :showDelete="false"
        :showCheckbox="false"
      >
        <qm-table-column field="userName">用户名称</qm-table-column>
        <qm-table-column field="deptName">所在部门</qm-table-column>
        <template v-slot:moreBtn="{ row }">
          <el-button @click="doRemove(row)">移除</el-button>
        </template>
      </qm-table>
    </el-dialog>
  </div>
</template>

<script>
import Controller from "@/libs/framework/controller";
import request from "@/utils/request";
import _ from "lodash";

export default class Instance extends Controller {
  onBeforeInit() {
    this.urls = {
      model: "/eip/shaky/getListModel",
      query: "/eip/shaky/query",
      save: "/eip/shaky/save",
      delete: "/eip/shaky/delete",
      entity: "/eip/shaky/getEntity",
    };
  }
  onBeforeSave(postModel) {
    return true;
  }
  mixin() {
    return {
      data() {
        return {
          sex: null,
          //分配用户dialog的数据
          dialogUserVisible: false,
          //下拉框数据
          users: [],
          deptTree: [],
          searchUsers: [],
          departmentId: null,
          names: "",
          //当前行对象
          row: {},
          rules: {
            model: {
              shakyName: [
                {
                  required: true,
                  message: "任务名称不能为空",
                  trigger: "blur",
                },
              ],
              leaveDay: [
                {
                  required: true,
                  message: "工作量时间不能为空",
                  trigger: "blur",
                },
              ],
              startDate: [
                { required: true, message: "请选择开始时间", trigger: "blur" },
              ],
              endDate: [
                { required: true, message: "请选择结束时间", trigger: "blur" },
              ],
            },
          },
        };
      },
      methods: {
        doRemove(row) {
          this.$confirm("确定要删除么？", "提示", {
            confirmButtonText: "确定",
            cancelButtonText: "取消",
            type: "warning",
          })
            .then(() => {
              request({
                url: "/eip/shaky/removeShakyMember",
                method: "post",
                data: {
                  shakyMember: row,
                },
              })
                .then((r) => {
                  if (r && !r.initMessage) {
                    this.$message({
                      message: "删除成功",
                      type: "success",
                    });
                    this.$refs["userTable"].refresh();
                  } else {
                    reject(r.initMessage || "数据请求失败");
                  }
                })
                .catch((e) => {
                  reject(e);
                });
            })
            .catch(() => {
              this.$message({
                type: "info",
                message: "已取消删除",
              });
            });
        },
        changeVa(model) {
          var startDate = model.startDate;
          var endDate = model.endDate;
          if (startDate != null && endDate != null) {
            var date1 = new Date(startDate).format("yyyy-MM-dd");
            var date2 = new Date(endDate).format("yyyy-MM-dd");
            if (date1 == date2) {
              request({
                url: "/eip/shaky/getHours",
                method: "get",
                params: {
                  startDate: startDate,
                  endDate: endDate,
                },
              })
                .then((r) => {
                  if (r.success) {
                    model.leaveDay = r.data;
                  } else {
                    this.$message({
                      message: r.message,
                      type: "error",
                    });
                  }
                })
                .catch((e) => {
                  reject(e);
                });
            } else {
              this.$message({
                message: "不能跨天选择喔。",
                type: "info",
              });
            }
          }
        },
        beforeQuery(parmas) {
          parmas.query.shakyId = this.row.shakyId;
        },
        dialogUserClose() {
          this.dialogUserVisible = false;
          this.searchUsers = [];
          this.departmentId = null;
          this.names = "";
          this.sex = null;
          this.row = {};
        },
        editFunction(row) {
          console.log(row);
        },
        handleCommand(row) {
          this.row = row;
          this.dialogUserVisible = true;
          this.remoteMethod();
          this.selectDep();
        },
        selectDep() {
          request({
            url: "/admin/sysDepartment/selectDep",
            method: "get",
          })
            .then((r) => {
              if (r && !r.initMessage) {
                this.deptTree = r;
              } else {
                reject(r.initMessage || "数据请求失败");
              }
            })
            .catch((e) => {
              reject(e);
            });
        },
        renderRule(data, row, column) {
          let find = this.super.$util.find(
            this.controlData.signRules,
            (item) => {
              return item.ruleId === data;
            }
          );
          return (find || {}).ruleName;
        },
        remoteMethod(query) {
          request({
            url: "/admin/sysRole/setUsers/userSelect2",
            method: "get",
            params: { term: query },
          })
            .then((r) => {
              if (r && !r.initMessage) {
                this.users = r.data.map((m) => {
                  return {
                    value: m.userId,
                    userId: m.userId,
                    label: m.userName,
                    loginId: m.loginId,
                    userName: m.userName,
                  };
                });
              } else {
                reject(r.initMessage || "数据请求失败");
              }
            })
            .catch((e) => {
              reject(e);
            });
        },
        addUsersByNames() {
          var names = this.names;
          if (names === "") {
            this.$message("请先输入姓名。");
            return;
          }
          //判断是否以，分隔
          if (names.indexOf("，") == -1) {
            var name = _.words(names);
            names = _.join(name, "，");
          }
          const loading = this.$loading({
            lock: true,
            text: "Loading",
            spinner: "el-icon-loading",
            background: "rgba(0, 0, 0, 0.7)",
          });
          request({
            url: "/eip/shaky/addUsersByNames",
            method: "post",
            data: {
              shakyId: this.row.shakyId,
              names: names,
            },
          })
            .then((r) => {
              if (r.success) {
                this.msgSuccess("添加成功!");
                this.names = "";
                this.$refs["userTable"].refresh();
                loading.close();
              }
            })
            .catch((e) => {
              reject(e);
            });
        },
        addUsersBySex() {
          if (this.sex === null) {
            this.$message("请选择性别。");
            return;
          }
          const loading = this.$loading({
            lock: true,
            text: "Loading",
            spinner: "el-icon-loading",
            background: "rgba(0, 0, 0, 0.7)",
          });
          request({
            url: "/eip/shaky/addUsersBySex",
            method: "post",
            data: {
              shakyId: this.row.shakyId,
              sex: this.sex,
            },
          })
            .then((r) => {
              if (r.success) {
                this.msgSuccess("添加成功!");
                this.sex = null;
                this.$refs["userTable"].refresh();
                loading.close();
              }
            })
            .catch((e) => {
              reject(e);
            });
        },
        addUsers() {
          if (null == this.searchUsers || this.searchUsers.length == 0) {
            this.$message("请先选择用户");
            return;
          }
          const loading = this.$loading({
            lock: true,
            text: "Loading",
            spinner: "el-icon-loading",
            background: "rgba(0, 0, 0, 0.7)",
          });
          var users = _.join(this.searchUsers, ",");
          request({
            url: "/eip/shaky/addUsers",
            method: "post",
            data: {
              shakyId: this.row.shakyId,
              users: users,
            },
          })
            .then((r) => {
              if (r.success) {
                this.msgSuccess("添加成功!");
                this.searchUsers = [];
                this.$refs["userTable"].refresh();
                loading.close();
              }
            })
            .catch((e) => {
              reject(e);
            });
        },
        batchAddUsers() {
          if (null == this.departmentId || this.departmentId.length == 0) {
            this.$message("请先选择一个部门!");
            return;
          }
          var departmentIds = [];
          for (var i = 0; i < this.departmentId.length; i++) {
            departmentIds.push(this.departmentId[i]);
          }
          var ids = _.join(departmentIds, ",");
          // let departmentId = this.departmentId[this.departmentId.length - 1];
          const loading = this.$loading({
            lock: true,
            text: "Loading",
            spinner: "el-icon-loading",
            background: "rgba(0, 0, 0, 0.7)",
          });
          request({
            url: "/eip/shaky/addUsersByDept",
            method: "post",
            data: {
              departmentId: ids,
              shakyId: this.row.shakyId,
            },
          })
            .then((r) => {
              if (r.success) {
                this.msgSuccess("添加成功");
                this.departmentId = null;
                this.$refs["userTable"].refresh();
                loading.close();
              }
            })
            .catch((e) => {
              reject(e);
            });
        },
      },
    };
  }
}
</script>

<style scoped lang="scss">
// .el-form-item {
//   margin-bottom: 10px;
// }
</style>
